﻿Imports System.Windows.Forms
Imports DevExpress.XtraEditors.Controls
Imports DevExpress.UserSkins
Imports DevExpress.Skins
Imports DevExpress.XtraEditors
Imports System.IO
Imports System.Runtime.InteropServices

Public Class BaseMain
    Public Sub New()

        ' This call is required by the Windows Form Designer.
        SkinManager.Default.RegisterAssembly(GetType(DevExpress.UserSkins.BonusSkins).Assembly)
        InitializeComponent()


        ' Add any initialization after the InitializeComponent() call.

    End Sub
    Private Sub ShowNewForm(ByVal sender As Object, ByVal e As EventArgs)
        ' Create a new instance of the child form.
        Dim ChildForm As New System.Windows.Forms.Form
        ' Make it a child of this MDI form before showing it.
        ChildForm.MdiParent = Me

        m_ChildFormNumber += 1
        ChildForm.Text = "Window " & m_ChildFormNumber

        ChildForm.Show()
    End Sub

    Private Sub OpenFile(ByVal sender As Object, ByVal e As EventArgs)
        Dim OpenFileDialog As New OpenFileDialog
        OpenFileDialog.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyDocuments
        OpenFileDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
        If (OpenFileDialog.ShowDialog(Me) = System.Windows.Forms.DialogResult.OK) Then
            Dim FileName As String = OpenFileDialog.FileName
            ' TODO: Add code here to open the file.
        End If
    End Sub

    Private Sub SaveAsToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim SaveFileDialog As New SaveFileDialog
        SaveFileDialog.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyDocuments
        SaveFileDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"

        If (SaveFileDialog.ShowDialog(Me) = System.Windows.Forms.DialogResult.OK) Then
            Dim FileName As String = SaveFileDialog.FileName
            ' TODO: Add code here to save the current contents of the form to a file.
        End If
    End Sub


    Private Sub ExitToolsStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs)
        Me.Close()
    End Sub

    Private Sub CutToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs)
        ' Use My.Computer.Clipboard to insert the selected text or images into the clipboard
    End Sub

    Private Sub CopyToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs)
        ' Use My.Computer.Clipboard to insert the selected text or images into the clipboard
    End Sub

    Private Sub PasteToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs)
        'Use My.Computer.Clipboard.GetText() or My.Computer.Clipboard.GetData to retrieve information from the clipboard.
    End Sub



    Private Sub CascadeToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs)
        Me.LayoutMdi(MdiLayout.Cascade)
    End Sub

    Private Sub TileVerticalToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs)
        Me.LayoutMdi(MdiLayout.TileVertical)
    End Sub

    Private Sub TileHorizontalToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs)
        Me.LayoutMdi(MdiLayout.TileHorizontal)
    End Sub

    Private Sub ArrangeIconsToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs)
        Me.LayoutMdi(MdiLayout.ArrangeIcons)
    End Sub

    Private Sub CloseAllToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs)
        ' Close all child forms of the parent.
        For Each ChildForm As Form In Me.MdiChildren
            ChildForm.Close()
        Next
    End Sub

    Private m_ChildFormNumber As Integer
    Private Function IndexOf(ByVal itemsCollection As ListBoxItemCollection, ByVal s As String) As Integer
        For i As Integer = 0 To itemsCollection.Count - 1
            If itemsCollection(i).ToString() = s Then
                Return i
            End If
        Next i
        Return -1
    End Function
    'Private Sub listBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
    '    MenuGroup.View = TryCast(sender.SelectedItem, DevExpress.XtraNavBar.ViewInfo.BaseViewInfoRegistrator)
    '    MenuGroup.ResetStyles()
    'End Sub
    Private constparam() As String = {"deskripsi", "logosekolah"}
    Private Sub Byte2Image(ByRef NewImage As Image, ByVal ByteArr() As Byte)
        '
        Dim ImageStream As MemoryStream
        Try

            If ByteArr.GetUpperBound(0) > 0 Then
                ImageStream = New MemoryStream(ByteArr)
                NewImage = Image.FromStream(ImageStream)
            Else
                NewImage = Nothing
            End If

        Catch ex As Exception

            NewImage = Nothing

        End Try

    End Sub
    Public Sub refreshdata()
        Dim dt As New DataTable
        If Utils.executeSP("proc_searchall", New Object() {"*", "videntitas", "deskripsi", ""}, dt) Then
            If Utils.RowExist(dt) Then
                FillData(dt)
            End If
        End If
    End Sub
    Private Sub FillData(ByVal dtin As DataTable)
        For Each Sctl As String In constparam
            Dim ctl As Control()
            ctl = Me.Controls.Find(Sctl, True)
            If ctl IsNot Nothing And ctl.Length > 0 Then
                If TypeOf ctl(0) Is MemoEdit Then
                    Dim ctlmemo As New MemoEdit
                    ctlmemo = CType(ctl(0), MemoEdit)
                    If IsDBNull(dtin(0)(Sctl)) Then
                        ctlmemo.Text = ""
                    Else
                        Dim rtb As New RichTextBox
                        rtb.Text = dtin(0)(Sctl)
                        ctlmemo.Lines = rtb.Lines
                        MemoEdit1.Lines = ctlmemo.Lines
                    End If
                ElseIf TypeOf ctl(0) Is TextEdit Then
                    If IsDBNull(dtin(0)(Sctl)) Then
                        ctl(0).Text = ""
                    Else
                        ctl(0).Text = dtin(0)(Sctl)
                    End If
                ElseIf TypeOf ctl(0) Is PictureBox Then
                    Dim ctlimage As New PictureBox
                    ctlimage = CType(ctl(0), PictureBox)
                    If IsDBNull(dtin(0)(Sctl)) Then
                        ctlimage.Image = Nothing
                    Else
                        Dim img As Image
                        img = Nothing
                        Byte2Image(img, dtin(0)(Sctl))
                        ctlimage.Image = img
                        ctlimage.SizeMode = PictureBoxSizeMode.StretchImage
                    End If
                End If
            End If
        Next
    End Sub
    Function getRoleExecute() As DataTable
        Dim dt As New DataTable
        If Utils.executeSP("proc_zroleexecute", New Object() {"get", Session.kodeRole, Convert.DBNull, Convert.DBNull, Convert.DBNull, Convert.DBNull}, dt) Then
            If Not Utils.RowExist(dt) Then
                dt = Nothing
            End If
        End If
        Return dt
    End Function

    Private Sub BaseMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If Me.WindowState = FormWindowState.Maximized Then
            btnMaximize.Text = "Restore"
        End If
        'Application.EnableVisualStyles()
        LocalSession.dtrole = New DataTable
        LocalSession.dtrole = getRoleExecute()

        CreateMenu()
        Dim listBox1 As New DevExpress.XtraEditors.ListBoxControl
        'AddHandler listBox1.SelectedIndexChanged, AddressOf listBox1_SelectedIndexChanged
        listBox1.Height = 356
        listBox1.Items.AddRange(TryCast(MenuGroup.AvailableNavBarViews.ToArray(GetType(Object)), Object()))
        listBox1.SelectedItem = "Skin:Liquid Sky"
        listBox1.SelectedIndex = IndexOf(listBox1.Items, "Skin:Liquid Sky")
        MenuGroup.View = TryCast(listBox1.SelectedItem, DevExpress.XtraNavBar.ViewInfo.BaseViewInfoRegistrator)

        MenuGroup.ResetStyles()
        DefaultLookAndFeel1.LookAndFeel.SkinName = "Liquid Sky"

        'refreshdata()
        Me.pnlUtama.Controls.Clear()
        Dim ctl As New HomePage
        ctl.Dock = DockStyle.Fill
        Me.pnlUtama.Controls.Add(ctl)
    End Sub

    Private Sub CreateMenu()
        Dim dtmenu As New DataTable
        If Utils.executeSP("proc_z_getrolemenu", New Object() {"role", Session.kodeRole}, dtmenu) Then
            'If executeSP("proc_z_getmenuform", New Object() {"get"}, dsmenu) Then
            If dtmenu.Rows.Count > 0 Then
                If Utils.RowExist(dtmenu) Then
                    Dim dtgroup As New DataTable
                    Try
                        dtgroup = dtmenu.Select("header = 0").CopyToDataTable
                    Catch ex As Exception

                    End Try
                    For Each r As DataRow In dtgroup.Rows
                        Dim navBarGroup As DevExpress.XtraNavBar.NavBarGroup = MenuGroup.Groups.Add()

                        navBarGroup.Caption = r("menuname").ToString
                        navBarGroup.Name = r("menuid").ToString

                        Dim dtdetail As New DataTable
                        Try
                            dtdetail = dtmenu.Select("header = '" & navBarGroup.Name & "'").CopyToDataTable
                        Catch ex As Exception

                        End Try
                        If Utils.RowExist(dtdetail) Then
                            For Each rd As DataRow In dtdetail.Rows
                                Dim item As DevExpress.XtraNavBar.NavBarItem = MenuGroup.Items.Add()
                                item.SmallImageIndex = rd("imageid")
                                'item.LargeImageIndex = item.SmallImageIndex
                                'i += 1
                                item.Caption = rd("menuname").ToString
                                item.Name = rd("menuid").ToString
                                item.Tag = rd("formname").ToString
                                AddHandler item.LinkClicked, AddressOf SelectedMenu_OnClick
                                navBarGroup.ItemLinks.Add(item)
                                navBarGroup.Expanded = True
                                'ExistSelectedItemLink()
                            Next

                        End If
                        'ChangeGroups()
                    Next


                End If
            End If
        End If
    End Sub
    Private Function DynamicallyLoadedObject(ByVal objectName As String, Optional ByVal args() As Object = Nothing) As Form
        Dim returnObj As Object = Nothing
        Dim ProjectName As String = Reflection.Assembly.GetExecutingAssembly.GetName.Name
        Dim Type As Type = Reflection.Assembly.GetExecutingAssembly().GetType(ProjectName & "." & objectName)
        If Type IsNot Nothing Then
            returnObj = Activator.CreateInstance(Type, args)
        End If
        Return returnObj
    End Function
    Private Sub ShowForm(ByVal FormName As String, ByVal IsDialog As Boolean)
        Dim f As Form = DynamicallyLoadedObject(FormName)
        If IsDialog = True Then
            For Each ChildForm As Form In Me.MdiChildren
                'If ChildForm.Name = f.Name Then
                ChildForm.Close()
                'End If
            Next

            f.MdiParent = Me
            'f.Top = 0
            'f.Left = 0

            f.Show()
            'f.BringToFront()
        Else
            MessageBox.Show("Menu tidak ditemukan", "Error", MessageBoxButtons.OK)

        End If
    End Sub
    Public Sub CloseForm(ByVal FormName As String)
        'Dim f As Form = DynamicallyLoadedObject(FormName)
        For Each ChildForm As Form In Me.MdiChildren
            If ChildForm.Name = FormName Then
                ChildForm.Close()
            End If
        Next
    End Sub
    Private Function GetControl(ByVal objectName As String, Optional ByVal args() As Object = Nothing) As Control
        Dim returnObj As Object = Nothing
        Dim ProjectName As String = Reflection.Assembly.GetExecutingAssembly.GetName.Name
        Dim Type As Type = Reflection.Assembly.GetExecutingAssembly().GetType(ProjectName & "." & objectName)
        If Type IsNot Nothing Then
            returnObj = Activator.CreateInstance(Type, args)
        End If
        Return returnObj
    End Function

    Private Sub SelectedMenu_OnClick(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim item As DevExpress.XtraNavBar.NavBarItem
        Dim vDiskripsi As String = ""
        item = CType(sender, DevExpress.XtraNavBar.NavBarItem)
        If item.Name = "home" Then

            Exit Sub
        ElseIf item.Name = "logout" Then
            Exit Sub
        End If

        LocalSession.PublicMenuId = item.Name
        ' ShowForm(item.Tag, True)
        Dim dtmenu As New DataTable
        If Utils.executeSP("proc_searchallEqual", New Object() {"*", "menu", "menuid", item.Name}, dtmenu) Then
            If Utils.RowExist(dtmenu) Then
                vDiskripsi = dtmenu(0)("description")
            End If
        End If

        
        
        Me.pnlUtama.Controls.Clear()
        Dim ctl As New PageTemplate
        ctl = GetControl(item.Tag)
        'ctl.Size = pnlUtama.Size
        ctl.Dock = DockStyle.Fill
        ctl.TitleHeader.Text = vDiskripsi
        Me.pnlUtama.Controls.Add(ctl)
        Me.pnlUtama.Refresh()
    End Sub

    Public Sub SetSelectMenu(ByVal formname As String, ByVal captionForm As String)
        ' ShowForm(item.Tag, True)
        Dim vDiskripsi As String = ""
        Dim dtmenu As New DataTable
        If Utils.executeSP("proc_searchallEqual", New Object() {"*", "menu", "formname", formname}, dtmenu) Then
            If Utils.RowExist(dtmenu) Then
                vDiskripsi = dtmenu(0)("description")
                LocalSession.PublicMenuId = dtmenu(0)("menuid")
            End If
        End If

        Me.pnlUtama.Controls.Clear()
        Dim ctl As New PageTemplate
        ctl = GetControl(formname)
        'ctl.Size = pnlUtama.Size
        ctl.Dock = DockStyle.Fill
        ctl.TitleHeader.Text = vDiskripsi
        Me.pnlUtama.Controls.Add(ctl)
        Me.pnlUtama.Refresh()
    End Sub
    Public Sub LoadPreviewReport(ByVal report As DevExpress.XtraReports.UI.XtraReport, ByVal ReportData As DataTable, ByVal vFormName As String, ByVal vHeaderTitle As String)
        Dim formname As String = "MainPreviewControl"
        ' ShowForm(item.Tag, True)
        Me.pnlUtama.Controls.Clear()
        Dim ctl As New MainPreviewControl
        ctl.FormName = vFormName
        ctl.HeaderTitle = vHeaderTitle
        ctl.MainLoad(report, ReportData)
        'ctl.report = report
        'ctl.DataSource = ReportData
        'ctl.Size = pnlUtama.Size
        ctl.Dock = DockStyle.Fill
        Me.pnlUtama.Controls.Add(ctl)
        Me.pnlUtama.Refresh()
    End Sub

    Public Sub LoadPreviewReports(ByVal ds As DataSet, ByVal vFormName As String, ByVal vHeaderTitle As String, ByVal noreport As Integer)
        Dim formname As String = "MainPreviewControl"
        Me.pnlUtama.Controls.Clear()
        Dim ctl As New MainPreviewControl
        ctl.FormName = vFormName
        ctl.HeaderTitle = vHeaderTitle
        ctl.MainLoadReport(ds, noreport)
        'ctl.Size = pnlUtama.Size
        ctl.Dock = DockStyle.Fill
        Me.pnlUtama.Controls.Add(ctl)
        Me.pnlUtama.Refresh()
    End Sub


    Private Sub BaseMain_FormClosed(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles MyBase.FormClosed
        'Application.Exit()
    End Sub

    Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
        'Me.Close()
        Application.Exit()
    End Sub

    Private Sub pnlUtama_Resize(ByVal sender As System.Object, ByVal e As System.EventArgs)

        For Each ctl As Control In pnlUtama.Controls
            If ctl.Name.StartsWith("Form") Then
                ctl.Size = pnlUtama.Size
            End If
        Next
    End Sub

    Private Sub btnMinimize_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMinimize.Click
        Me.WindowState = FormWindowState.Minimized
    End Sub

    Private Sub btnMaximize_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMaximize.Click
        If Me.WindowState = FormWindowState.Maximized Then
            Me.WindowState = FormWindowState.Normal
            btnMaximize.Text = "Max"
            'Me.FormBorderStyle = Windows.Forms.FormBorderStyle.FixedToolWindow
            Me.Text = ""
            'Me.StartPosition = FormStartPosition.CenterScreen
        Else
            Me.WindowState = FormWindowState.Maximized
            btnMaximize.Text = "Restore"
            'Me.FormBorderStyle = Windows.Forms.FormBorderStyle.None
        End If

    End Sub


    Private Sub home_LinkClicked(ByVal sender As System.Object, ByVal e As DevExpress.XtraNavBar.NavBarLinkEventArgs) Handles home.LinkClicked
        Me.pnlUtama.Controls.Clear()
        Dim ctl As New HomePage
        ctl.Dock = DockStyle.Fill
        Me.pnlUtama.Controls.Add(ctl)
    End Sub

    Private Sub logout_LinkClicked(ByVal sender As System.Object, ByVal e As DevExpress.XtraNavBar.NavBarLinkEventArgs) Handles logout.LinkClicked
        If MsgBox("Apakah Anda Akan LogOut ?", MsgBoxStyle.YesNo, "Log Out Confirmation") = MsgBoxResult.Yes Then
            LoginForm.Visible = True
            Me.Close()
        End If

    End Sub

    Private Sub BaseMain_Resize(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Resize

    End Sub
    <DllImport("user32.dll")> _
    Public Shared Function ReleaseCapture() As Boolean
    End Function

    <DllImport("user32.dll")> _
    Public Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal Msg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer
    End Function

    Private Const WM_NCLBUTTONDOWN As Integer = &HA1
    Private Const HTBORDER As Integer = 18
    Private Const HTBOTTOM As Integer = 15
    Private Const HTBOTTOMLEFT As Integer = 16
    Private Const HTBOTTOMRIGHT As Integer = 17
    Private Const HTCAPTION As Integer = 2
    Private Const HTLEFT As Integer = 10
    Private Const HTRIGHT As Integer = 11
    Private Const HTTOP As Integer = 12
    Private Const HTTOPLEFT As Integer = 13
    Private Const HTTOPRIGHT As Integer = 14

    Private Sub MoveControl(ByVal hWnd As IntPtr)
        ReleaseCapture()
        SendMessage(hWnd, WM_NCLBUTTONDOWN, HTCAPTION, 0)
    End Sub
    Private Sub ResizeForm(ByVal direction As ResizeDirection)
        Dim dir As Integer = -1
        Select Case direction
            Case ResizeDirection.Left
                dir = HTLEFT
            Case ResizeDirection.TopLeft
                dir = HTTOPLEFT
            Case ResizeDirection.Top
                dir = HTTOP
            Case ResizeDirection.TopRight
                dir = HTTOPRIGHT
            Case ResizeDirection.Right
                dir = HTRIGHT
            Case ResizeDirection.BottomRight
                dir = HTBOTTOMRIGHT
            Case ResizeDirection.Bottom
                dir = HTBOTTOM
            Case ResizeDirection.BottomLeft
                dir = HTBOTTOMLEFT
        End Select

        If dir <> -1 Then
            ReleaseCapture()
            SendMessage(Me.Handle, WM_NCLBUTTONDOWN, dir, 0)
        End If

    End Sub
    Public Enum ResizeDirection
        None = 0
        Left = 1
        TopLeft = 2
        Top = 4
        TopRight = 8
        Right = 16
        BottomRight = 32
        Bottom = 64
        BottomLeft = 128
    End Enum
    Private Const BorderWidth As Integer = 6

    Private _resizeDir As ResizeDirection = ResizeDirection.None

    Private Property resizeDir() As ResizeDirection
        Get
            Return _resizeDir
        End Get
        Set(ByVal value As ResizeDirection)
            _resizeDir = value

            'Change cursor
            Select Case value
                Case ResizeDirection.Left
                    Me.Cursor = Cursors.SizeWE

                Case ResizeDirection.Right
                    Me.Cursor = Cursors.SizeWE

                Case ResizeDirection.Top
                    Me.Cursor = Cursors.SizeNS

                Case ResizeDirection.Bottom
                    Me.Cursor = Cursors.SizeNS

                Case ResizeDirection.BottomLeft
                    Me.Cursor = Cursors.SizeNESW

                Case ResizeDirection.TopRight
                    Me.Cursor = Cursors.SizeNESW

                Case ResizeDirection.BottomRight
                    Me.Cursor = Cursors.SizeNWSE

                Case ResizeDirection.TopLeft
                    Me.Cursor = Cursors.SizeNWSE

                Case Else
                    Me.Cursor = Cursors.Default
            End Select
        End Set
    End Property

    Private Sub Panel1_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Panel1.MouseDown
        If e.Button = Windows.Forms.MouseButtons.Left Then
            If Me.Width - BorderWidth > e.Location.X AndAlso e.Location.X > BorderWidth AndAlso e.Location.Y > BorderWidth Then
                MoveControl(Me.Handle)
                btnMaximize.Text = "Max"
            Else
                If Me.WindowState <> FormWindowState.Maximized Then
                    ResizeForm(resizeDir)


                End If
            End If
        End If
    End Sub

    Private Sub Panel1_MouseMove(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Panel1.MouseMove
        If e.Location.X < BorderWidth And e.Location.Y < BorderWidth Then
            resizeDir = ResizeDirection.TopLeft

        ElseIf e.Location.X < BorderWidth And e.Location.Y > Me.Height - BorderWidth Then
            resizeDir = ResizeDirection.BottomLeft

        ElseIf e.Location.X > Me.Width - BorderWidth And e.Location.Y > Me.Height - BorderWidth Then
            resizeDir = ResizeDirection.BottomRight

        ElseIf e.Location.X > Me.Width - BorderWidth And e.Location.Y < BorderWidth Then
            resizeDir = ResizeDirection.TopRight

        ElseIf e.Location.X < BorderWidth Then
            resizeDir = ResizeDirection.Left

        ElseIf e.Location.X > Me.Width - BorderWidth Then
            resizeDir = ResizeDirection.Right

        ElseIf e.Location.Y < BorderWidth Then
            resizeDir = ResizeDirection.Top

        ElseIf e.Location.Y > Me.Height - BorderWidth Then
            resizeDir = ResizeDirection.Bottom

        Else
            resizeDir = ResizeDirection.None
        End If
    End Sub
End Class
